const express = require('express')
var app = express()
const UserRouter = require('./routers/user')
const MenuRouter = require('./routers/menu')
const MangerRouter = require('./routers/manger')
const cors = require('cors')
app.use(cors())
    //
const jwt = require('express-jwt')
const privateKey = require('./tokenprivatekey/key')
const cb = require('./promise/cb')
const bodyparser = require('body-parser')
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended: true }))

//信息返回的中间件
app.use((req, res, next) => {
    res.ResInfo = function(err, status = 500, data = {}) {
        res.send({
            meta: {
                message: err instanceof Error ? err.message : err, //如果是系统错误则返回系统错误信息，否则返回自定义错误
                status,
            },

            data: data
        })
    }
    next()
})
app.use(jwt({ secret: privateKey.key, algorithms: ['HS256'] }).unless({ path: [/^\/api\//] }))
app.use('/api', UserRouter)
app.use('/api', MenuRouter)
app.use('/api', MangerRouter)
app.use('/api', cb)
    // app.get('/test', async(req, res) => {
    //     const sql = "select count(*) as count from  sp_manager"
    //     const ress = await cb(sql)
    //     res.ResInfo(ress)
    // })

const Jio = require('joi')

app.use(function(err, req, res, next) {
    if (err instanceof Jio.ValidationError) {
        return res.ResInfo(err);
    }
    if (err.name === 'UnauthorizedError') {
        return res.ResInfo('身份认证错误')
    }


})
app.listen(8888, () => {
    console.log('server running at http://127.0.0.1:8888')
})